<template>
  <basic-container>
    <div class="app-container calendar-list-container">
      <avue-crud :option="option" ref="crud" v-model="form" :page="page" @on-load="getList" :table-loading="listLoading" @search-change="handleFilter" @refresh-change="handleRefreshChange" @row-update="handleUpdate" @row-save="handleSave" :before-open="handleOpenBefore" :data="list">
        <template slot-scope="scope" slot="menuLeft">
          <el-button v-if="permissions.sys_user_add" class="filter-item" style="margin-left: 10px;" @click="handleCreate" size="small" type="primary" icon="el-icon-edit">添加</el-button>
        </template>
        <template slot="community" slot-scope="scope">
          <span v-for="(item,index) in scope.row.communityList" :key="index">
            <span v-if="index>0">
              &
            </span>
            {{item.communityName}}
          </span>
        </template>
        <template slot="username" slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
        <template slot="role" slot-scope="scope">
          <span v-for="(role,index) in scope.row.roleList" :key="index">
            {{role.roleName}}
          </span>
        </template>
        <template slot="delFlag" slot-scope="scope">
          <el-tag>{{scope.label}}</el-tag>
        </template>
        <template slot-scope="scope" slot="menu">
          <!-- <el-button size="small" type="text" icon="el-icon-view" @click="$refs.guard.handleAddIC(scope.row,scope.row.$index)">IC信息维护</el-button> -->
          <el-button v-if="permissions.sys_user_upd" size="small" type="text" icon="el-icon-edit" @click="handleEdit(scope.row,scope.index)">编 辑
          </el-button>
          <el-button v-if="permissions.sys_user_del" size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row,scope.index)">删 除
          </el-button>
        </template>
        <template slot="communityForm" slot-scope="scope">
          <el-cascader :options="deptDic" @change="handleChange" :show-all-levels="false">
          </el-cascader>
          <!-- <el-select class="filter-item" v-model="form.community" placeholder="请选择企业" :disabled="scope.disabled">
            <el-select v-for="group in deptDic" :key="group.label" :label="group.label">
              <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-select> -->
        </template>
        <template slot="roleForm" slot-scope="scope">
          <avue-crud-select v-model="form.role" multiple :disabled="scope.disabled" placeholder="请选择角色" :dic="rolesDic" :props="roleProps"></avue-crud-select>
        </template>
      </avue-crud>
      <guard ref="guard"></guard>
    </div>
  </basic-container>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/user'
import { getToken, setToken, removeToken, getFileIp } from '@/util/auth'
import {
  deptRoleList,
  fetchDeptTree,
  getCommunitysByCurrentUser,
  getCommunityObj
} from '@/api/role'
import { mapGetters } from 'vuex'
import option from '@/const/crud/user'
import guard from './guard'
export default {
  name: 'table_user',
  components: {
    guard
  },
  data() {
    return {
      createCount: false,
      treeDeptData: [],
      option: option,
      roleProps: {
        label: 'roleName',
        value: 'roleId'
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条,
        isAsc: false //是否倒序
      },
      list: [],
      deptDic: [],
      rolesDic: [],
      listLoading: true,
      dialogDeptVisible: false,
      form: {}
    }
  },
  watch: {
    'form.deptId'() {
      this.createCount++
      if (this.createCount > 1) {
        this.form.role = []
        if (this.form.deptId != null) {
          this.deptRoleList()
        }
      }
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created() {
    this.init()
  },
  methods: {
    handleChange(value) {
      this.form.community = []
      // console.log(value[value.length - 1])
      this.form.community.push(value[value.length - 1])
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data
      })
      this.dialogDeptVisible = true
    },
    //初始化
    init() {
      this.fetchDeptTree()
    },
    //获取列表
    getList(page, params = {}) {
      this.listLoading = true
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params
        )
      ).then(response => {
        const data = response.data
        this.list = data.records
        this.page.total = data.total
        this.listLoading = false
      })
    },
    // 搜索回调参数
    handleFilter(param) {
      this.page.page = 1
      this.getList(this.page, param)
    },
    //刷新回调用
    handleRefreshChange() {
      this.getList(this.page)
    },
    // 打开弹窗的回调
    handleOpenBefore(show, type) {
      if (['edit', 'views'].includes(type)) {
        this.createCount = 0
        //组装角色和小区多选数组
        this.form.community = this.form.communityList.map(ele => {
          return ele.communityId
        })
        this.form.role = this.form.roleList.map(ele => {
          return ele.roleId
        })
        this.deptRoleList()
      } else if (type === 'add') {
        this.createCount = 1
        //新增清空角色列表数据
        this.form.community = []
        this.rolesDic = []
      }
      show()
    },

    //获取园区/公司列表
    fetchDeptTree() {
      fetchDeptTree().then(response => {
        this.deptDic = response.data
      })
    },
    // communityChange() {
    //   this.form.role = []
    // },
    //获取园区id获取角色
    deptRoleList() {
      deptRoleList(this.form.deptId).then(response => {
        if (response.data == '') {
          this.rolesDic = []
        } else {
          this.rolesDic = response.data
        }
      })
    },
    handleCreate() {
      this.$refs.crud.rowAdd()
    },
    handleEdit(row, index) {
      //调用crud内部的方法
      this.$refs.crud.rowEdit(row, index)
      this.form.password = undefined
    },
    /**
     * 删除方法
     * @param row当前行数据
     * @param index为第几行数据
     */
    handleDelete(row, index) {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.getList(this.page)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    /**
     * 保存方法
     * @description 注意如果请求失败调用loading关闭等待
     * @param row当前行数据
     * @param done关闭窗口
     * @param loading 关闭等待
     */
    handleSave(row, done, loading) {
      addObj(this.form).then(res => {
        if (!res.data.data) {
          loading()
          this.$notify({
            title: '添加失败',
            message: res.data.msg,
            type: 'faile',
            duration: 2000
          })
          return
        }
        done()
        this.getList(this.page)
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    /**
     * 更新方法
     * @description 注意如果请求失败调用loading关闭等待
     * @param row当前行数据
     * @param index为第几行数据
     * @param done关闭窗口
     * @param loading 关闭等待
     */
    handleUpdate(row, index, done, loading) {
      putObj(this.form).then(res => {
        if (!res.data.data) {
          loading()
          this.$notify({
            title: '修改失败',
            message: res.data.msg,
            type: 'faile',
            duration: 2000
          })
          return
        }
        done()
        this.getList(this.page)
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>